<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link href="order_list.css" rel="stylesheet" type="text/css">
    <script src="jquery-2.1.3.min.js"></script>
    <script src="d3.min.js"></script>
    <script src="common.js"></script>
    <script src="jquery.qrcode-0.11.0.min.js"></script>
</head>
<body>
<div id="myalipay"></div>
<label><a>今日折扣:</a><a id="discount_rate"></a></label>

    <table class="order-array table1">
        <thead>
            <tr>

            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
    <input id="split-with" type="text" value="99:40 48:16 28:10 15:5" placeholder="格式:price:discount p2,d2 ...">
    <input class="lock menu-status" type="button" value="">

    <table class="split-array table1">
        <thead>
            <tr>

            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>

<script>

    (function() {
        $.get(server_host + '/api/split_menu/show').success(function(strData){
            var status_btn = $('.menu-status')
            if(strData==""){

                status_btn.removeClass("unlock")
                status_btn.addClass("lock")
                status_btn.val("锁")

            }
            else {
                status_btn.removeClass("lock")
                status_btn.addClass("unlock")
                status_btn.val("解锁")

                var data = JSON.parse(strData)

            }
        });
        $.get(server_host + '/api/today_order_form').success(function(strData){
            var data = JSON.parse(strData)
            // table
            var tab = d3.select('.order-array')
            // title
            var head_tr = tab.select('tr')
            head_tr.append("th")
            head_tr.selectAll("th.menu-name")
                    .data(data['menu_names'])
                    .enter()
                    .append('th')
                    .attr('class', function(d, i) {
                        return 'menu-name x-' + i
                    })
                    .attr('unit', function(d, i){
                        return d[1]
                    })
                    .attr('name', function(d, i){
                        return d[0]
                    })
                    .text(function(d, i){
                        return d[0] +'(' + d[1] + ')';
                    });
            head_tr.append('th')
                    .attr('class', 'x-all')
                    .text('合计')
            head_tr.append('th')
                    .attr('class', 'x-discount')
                    .text('折扣后')
            // body
            var body = tab.select('tbody')
            //line
            var body_tr = body.selectAll('th.user-data')
                    .data(data['user_names'])
                    .enter()
                    .append('tr')
                    .attr('y', function(d, i){
                        return i;
                    })
                    .attr('class', 'user-data')
            //line title
            body_tr.append('th')
                    .attr('class', 'user-name')
                    .text(function(d, i){
                        return d;
                    });
            // element
            var ele_td = body_tr.selectAll('td.ele')
                    .data(function(d, i){
                        return data['matrix'][i];
                    })
                    .enter()
                    .append('td')
                    .attr('class', function(d, i) {
                        return  'ele ' + "x-" + i
                    })
                    .attr('x', function(d, i){
                        return i
                    })
            ele_td.append('a')
                    .attr('class', 'dip-num change_num')
                    .attr('value', '-1')
                    .attr('href', 'javascript:;')
                    .text('-')
            ele_td.append('a')
                    .attr('class', 'num')
                    .text(function(d, i){
                        if(d == 0)
                            return ""
                        else
                            return d;
                    });
            ele_td.append('a')
                    .attr('class', 'add-num change_num')
                    .attr('value', '1')
                    .attr('href', 'javascript:;')
                    .text('+')

            body_tr.append('td')
                    .attr('class', 'x-amount')
                    .attr('amount', function(d, i){
                        var my_tr = d3.select(this.parentNode)
                        var amount  = 0
                        my_tr.selectAll('td.ele')
                                .each(function() {
                                    amount += Number(d3.select(this).select('.num').text())
                                });
                        return amount;
                    })
                    .attr('sum', function(d, i){
                        var my_tr = d3.select(this.parentNode)
                        var sum = 0
                        my_tr.selectAll('td.ele')
                                .each(function() {
                                    var num = Number(d3.select(this).select('.num').text())
                                    var x_val = d3.select(this).attr('x')
                                    var x_th = head_tr.select("th.x-" + x_val)
                                    sum += Number(x_th.attr('unit')) * num
                                });
                        return sum;
                    })
                    .text(function(){
                        var i = d3.select(this)
                        return i.attr('amount') + '(￥' + i.attr('sum') +  ')'
                    })
            var amount_tr = body.append('tr')
                    .attr('class', 'user-amount')
            amount_tr.append('th')
                    .attr('class', 'y-all')
                    .text('合计')
            amount_tr.selectAll('td.y-amount')
                    .data(data['menu_names'])
                    .enter()
                    .append('td')
                    .attr('class', 'y-amount')
                    .attr('amount', function(d, i){
                        var amount = 0
                        body_tr.selectAll('td.ele.x-' + i)
                                .each(function() {
                                    amount += Number(d3.select(this).select('.num').text())
                                })
                        return amount;
                    })
                    .attr('sum', function(d, i) {
                        var sum = 0
                        body_tr.selectAll('td.ele.x-' + i)
                                .each(function() {
                                    var num = Number(d3.select(this).select('.num').text())
                                    sum += d[1] * num
                                })
                        return sum;
                    })
                    .text(function(){
                        var i = d3.select(this)
                        return i.attr('amount') + '(￥' + i.attr('sum') +  ')'
                    });
            var all_amount_tr = amount_tr.append('td')
                    .attr('class', 'all-amount')
                    .attr('amount', function(){
                        var amount = 0
                        amount_tr.selectAll('td.y-amount').each(function () {
                            amount += Number(d3.select(this).attr('amount'))
                        })
                        return amount
                    })
                    .attr('sum', function() {
                        var sum = 0
                        amount_tr.selectAll('td.y-amount').each(function () {
                            sum += Number(d3.select(this).attr('sum'))
                        })
                        return sum
                    })
                    .text(function(){
                        var i =  d3.select(this)
                        return i.attr('amount') + '(￥' + i.attr('sum') +  ')'
                    })


            //贪心算法 分发订单
//            {
//
//                var all_menu = amount_tr.selectAll('.y-amount')
//                var eee = [30, 50, 99]
//
//                var limit = 2
//                var _sum = Number(all_amount_tr.attr("sum"))
//                var ideal_model = []
//
//                for (var i=0;i != limit && _sum > 0;++i){
//                    if (_sum<eee[0]){
//                        ideal_model.push(_sum)
//                        _sum = 0
//                        break
//                    }
//                    for (var j=eee.length;j > 0;--j){
//                        if(_sum >= eee[j-1] ){
//                            ideal_model.push(eee[j-1])
//                            _sum -= eee[j-1]
//                            break
//                        }
//                    }
//                }
//
//                if (_sum)
//                    ideal_model[ideal_model.length-1] += _sum;
//                console.log(JSON.stringify(ideal_model))
//                var all_menu_dict = {} // construct -> unit:[amount, obj0, obj1, ...]
//                all_menu.each(function(d, i){
//                    var own = d3.select(this)
////                    (own.data()+','+own.attr('amount'))
//                    if ( !(String(d[1]) in all_menu_dict)){
//                        all_menu_dict[String(d[1])] = new Array()
//                        all_menu_dict[String(d[1])].push(0)
//                    }
//                    all_menu_dict[String(d[1])][0] += Number(own.attr('amount'))
//                    all_menu_dict[String(d[1])].push(own)
//                })
//                var all_menu_arr = [] //construct -> [unit, [amount, obj0, obj1, ...]]
//                for(var k in all_menu_dict){
//                    all_menu_arr.push([k, all_menu_dict[k]]);
//                }
//                all_menu_arr.sort(function(a, b){return Number(b[0])-Number(a[0])})
//                var cursor = 0
//                var actual_model = new Array(ideal_model.length) // construct -> [[[unit,amount]]]
//                for (var i = 0; i != actual_model.length; ++i){
//                    actual_model[i] = []
//                }
////                actual_model[3]=2
//                //fill the actual_model[0]
//                for(var i = 0; i!= all_menu_arr.length; ++i){
//                    actual_model[cursor].push([all_menu_arr[i][0], all_menu_arr[i][1][0]])
//                }
//
//                var f =  function(arr, i){
//                    var sum = 0
//                    for (var i = 0; i != arr.length; ++i){
//                        sum += arr[i][0] * arr[i][1]
//                    }
//                    if (sum == ideal_model[i])
//                        return sum, arr;
//
//
//                    for(var i = arr.length; i != 0; --i){
//
//                        for (var j = arr[i-1].length; j != 0; --j){
//                            var sub = arr.slice()
//                            sub[i-1] = j-1
//                            var ret = f(sub, i)
//                            if (ret==0){
//                                arr=sub
//                                return 0;
//                            }
//                            else if(ret < 0){
//                                arr[i-1] ==
//                            }
//                        }
//                    }
//                }
//                f(actual_model)
//                for(var i = actual_model.length; i != 0; --i){
//                    f(actual_model[i], i)
//                }
//            }
            // event

            $.get(server_host + '/api/split_menu/show').success(function(strData){
                var status_btn = $('.menu-status')
                var split_with = $('#split-with')
                if(strData==""){
                    status_btn.removeClass("unlock")
                    status_btn.addClass("lock")
                    status_btn.val("锁")
                    split_with.show()
                    $(document).on('mouseenter', '.order-array td.ele', function(e){
                        d3.select(this).selectAll('.change_num').style("visibility", 'inherit')
                    })
                    $(document).on('mouseleave', '.order-array td.ele', function(e){
                        d3.select(this).selectAll('.change_num').style("visibility", 'hidden')
                    })
                    $(document).on('click', '.order-array td.ele .change_num', function(e){
                        var _ele_this = d3.select(this)
                        var _ele_td = d3.select(this.parentNode)
                        var _ele_tr = d3.select(this.parentNode.parentNode)

                        var user_name = data['user_names'][Number(_ele_tr.attr('y'))]
                        var menu_name = data['menu_names'][Number(_ele_td.attr('x'))][0]
                        var menu_unit = data['menu_names'][Number(_ele_td.attr('x'))][1]
                        var menu_amount = Number(_ele_this.attr('value'))

                        if (!Number(_ele_td.select('.num').text()) && menu_amount < 0){
                            return ;
                        }

                        var menu_list = [{
                            'name': menu_name,
                            'unit': menu_unit,
                            'amount': menu_amount
                        }]
                        var server_addr = server_host + "/api/add_menu?name="
                                + encodeURIComponent(user_name)
                                + "&menu="
                                + encodeURIComponent(JSON.stringify(menu_list))
                        _ele_this.attr("href", server_addr)
                    })

                }
                else {
                    status_btn.removeClass("lock")
                    status_btn.addClass("unlock")
                    status_btn.val("解锁")
                    split_with.hide()
                    var split_data = JSON.parse(strData)
                    var split_table = d3.select(".split-array")
                    //---------------------    discount    -------------
                    var discount_rate = d3.select('#discount_rate')
                    discount_rate.text(split_data['discount_rate'])
                    body_tr.append('td')
                            .attr('class', 'x-discount')
                            .attr('discount', function(){
                                var my_tr = d3.select(this.parentNode)
                                var sum = Number(my_tr.select('.x-amount').attr('sum'))
                                return Math.ceil( sum * split_data['discount_rate'] * 10 )/10.0
                            })
                            .text(function(d){
                                var i = d3.select(this)
                                return '￥' + i.attr('discount')
                            })
                    //----------------------     table       -------------
                    // title
                    var split_head_tr = split_table.select('thead')
                            .select('tr')
                    split_head_tr.append('th')
                    split_head_tr.selectAll('th.menu-name')
                            .data(split_data['menu_names'])
                            .enter()
                            .append('th')
                            .attr('class', function(d, i){
                                return 'menu-name x-' + i
                            })
                            .attr('unit', function(d){
                                return d[1]
                            })
                            .text(function(d, i){
                                return d[0] + '(' + d[1] + ')'
                            })
                    split_head_tr.append('th')
                            .attr('class', 'x-all')
                            .text('合计')
                    //body
                    var split_body_tr = split_table.select('tbody')
                            .selectAll('tr.split-index')
                            .data(split_data['fuck_js'])
                            .enter()
                            .append('tr')
                            .attr('class', function(d, i){
                                return 'split-index y-' + i
                            })
                    split_body_tr.append('th')
                            .text(function(d){
                                return '订单' + (d + 1)
                            })
                    split_body_tr.selectAll('td.ele')
                            .data(function(d, i){
                                return split_data['matrix'][i]
                            })
                            .enter()
                            .append('td')
                            .attr('class', 'ele')
                            .attr('x', function(d, i){
                                return i
                            })
                            .attr('value', function(d){
                                return d
                            })
                            .text(function(d){
                                if(!d)
                                    return ''
                                return d
                            })
                    split_body_tr.append('td')
                            .attr('class', 'x-amount')
                            .attr('amount', function(d, i){
                                var my_tr = d3.select(this.parentNode)
                                var amount  = 0
                                my_tr.selectAll('td.ele')
                                        .each(function() {
                                            amount += Number(d3.select(this).text())
                                        });
                                return amount;
                            })
                            .attr('sum', function(d, i){
                                var my_tr = d3.select(this.parentNode)
                                var sum = 0
                                my_tr.selectAll('td.ele')
                                        .each(function() {
                                            var num = Number(d3.select(this).text())
                                            var x_val = d3.select(this).attr('x')
                                            var x_th = split_head_tr.select("th.x-" + x_val)
                                            sum += Number(x_th.attr('unit')) * num
                                        });
                                return sum;
                            })
                            .text(function(){
                                var i = d3.select(this)
                                return i.attr('amount') + '(￥' + i.attr('sum') +  ')'
                            })
                }
            });


            $(document).on('click', '.lock', function(e){
                var split_with = $('#split-with').val()
                $.get(
                        server_host + '/api/split_menu/create',
                        {'split_with': split_with}
                ).success(function(strData){
                    alert('错定成功！')
                    location.reload()
                })
            })

            $(document).on('click', '.unlock', function(e){
                $.get(server_host + '/api/split_menu/clean').success(function(strData){
                    alert('解锁成功！')
                    location.reload()
                })
            })

        })

    //qrcode
        $('#myalipay').qrcode({
            "width": 100,
            "height": 100,
            "color": "#3a3",
            "text": alipay_url,
            "ecLevel": "H",
            "radius": 0.5,
            //
            "label": qrcode_tips,
            "mode": 2,
            "mSize": 0.11,
            "mPosX": 0.5,
            "mPosY": 0.5,
            "fontname": "Ubuntu",
            "fontcolor": "#ff9818"

        });
    }());
</script>
</body>
</html>